﻿var t_arr = new Array(); //选择的视图数组，Array【表名】
var c_arr = new Array(); //选择的列字段2唯数组，Array【表名】【表名.字段名】
var c_arr_all = new Array(); //选择的列字段2唯全字段数组，Array【表名】【字段名】
var on_Arr = new Array();
var where_Arr = new Array();
var order_Arr = new Array();
var viewAll = true;
var str_Arr = new Array();
//页面方法---begin
function Save() {
    $.post("/SystemConfiguration/SaveItem", { query: jv.GetDivJson($("#formArea"), 4) }, function (res) {
        alert(res);
    });
}
function back() {
    window.location.href = "/SystemConfiguration/ViewList";
}

//页面方法---end

//配置方法---begin
//
function select_All() {
    var selector = $("#selectView input");
    if ($("#select_All").is(':checked')) {
        selector.attr("checked", "checked");
        if (selector.length > 3) {
            lockJoin();
        }
    }
    else {
        selector.removeAttr("checked");
        UnlockJoin();
    }
    selector.each(function (i, d) {
        var nm = d.className;
        if (jv.IsNull(nm)) return;
        
    });
}


function lockJoin() {
    $("#viewShip input").attr("disabled", true);
    $("#viewShip input[value='INNER JOIN']").attr("checked", "checked");
}
function UnlockJoin() {
    $("#viewShip input").attr("disabled", false);
}

function InInfo() {
    var intdex = 1;
    var selector = $("#view_left input:checked");
    selector.each(function (i, d) {
        var html = "<tr id=tr1"+d.id+">";
        var id = "tr" + d.id;
        html += $("#" + id).html();
        html += "<td><a href=\"javascript:void(0)\" onclick=\"open1('"+ d.value+"');\">配置</a></td></tr>";
        $("#selectView1").append(html);
        $("#tr" + d.id).remove();
    });
//    alert($("#view_left input:checked").length);

}
function OutInfo() {
    var intdex = 1;
    var selector = $("#selectView1 input:checked");
    selector.each(function (i, d) {

        $("#tr1" + d.id).remove();
        $("#tr" + d.id).show();
    });
}

//$(function () {
//    
//    $.post("/SysTBView/SavedView/?id=" + id + "&index=0", function(res) {
//        if (res != "") {
//            for (var i = 0; i < eval(res).length; i++) {
//                var id = eval(res)[i].BaseViewID;
//                if ($("#" + id).length > 0) {
//                    $("#" + id).attr("checked", "checked");
//                    selectItem(id, $("#" + id)[0].className);
//                    //select_Table_All(id, $("#" + id)[0].className);
//                }
//            }
//        }
//    });
//});



function table_Close(id, en) {
    $("#select_All").removeAttr("checked");
    $("#" + id).removeAttr("checked");
    $("#div_" + id).remove();
    var index = t_arr.indexOf(en);
    t_arr.removeAt(index);
    c_arr.removeAt(index);
    if (t_arr.length <= 2)
        UnlockJoin();
    ShowDefinition();
}

function ShowDefinition(useOn) {
    if (c_arr.length > 0 && c_arr[0].length > 0) {
        var definition = "";
        if (useOn) {
            //--------Check Where------------
            var grp = false; //是否分组
            var defGroup = "";
            var defSelect = c_arr;
            var defWhere = new Array();
            var defHaving = new Array();
            for (var i = 0; i < where_Arr.length; i++) {
                if (where_Arr[i][3] != "") {
                    grp = true;
                }
            }
            if (grp) {
                defGroup = " GROUP BY " + defSelect.join(",");
            }
            for (var i = 0; i < where_Arr.length; i++) {
                if (grp) {
                    if (where_Arr[i][3] == "Where")
                        defWhere.push(where_Arr[i][0] + where_Arr[i][1] + where_Arr[i][2]);
                    else if (where_Arr[i][3] != "") {
                        if (defGroup.indexOf(where_Arr[i][0]) == -1)
                            defGroup += "," + where_Arr[i][0];
                        var exf = where_Arr[i][3] + "(" + where_Arr[i][0] + ")";
                        var exfc = where_Arr[i][0].substr(where_Arr[i][0].lastIndexOf(".") + 1);
                        defHaving.push(exf + where_Arr[i][1] + where_Arr[i][2]);
                        for (var j = 0; j < defSelect.length; j++) {
                            for (var k = 0; k < defSelect[j].length; k++) {
                                if (defSelect[j][k] == where_Arr[i][0]) {
                                    defSelect[j][k] = exf + " as " + exfc;
                                }
                            }
                        }
                    }
                    else if (where_Arr[i][3] == "") {
                        if (defGroup.indexOf(where_Arr[i][0]) == -1)
                            defGroup += "," + where_Arr[i][0];
                        defHaving.push(where_Arr[i][0] + where_Arr[i][1] + where_Arr[i][2]);
                    }
                }
                else {
                    defWhere.push(where_Arr[i][0] + where_Arr[i][1] + where_Arr[i][2]);
                }
            }
            //--------Definition Sql------------
            var ship = " " + $('#viewShip input:radio:checked').val() + " "; //Join sql
            definition = "SELECT " + defSelect.join(",");

            //--On sql
            definition += " FROM " + t_arr[0];
            var onErr = false;
            for (var i = 1; i < t_arr.length; i++) {
                onErr = true;
                definition += " INNER JOIN " + t_arr[i] + " ON ";
                for (var j = 0; j < on_Arr.length; j++) {
                    if (CheckArray(t_arr, i, on_Arr[j][0].substr(0, on_Arr[j][0].lastIndexOf("."))) && CheckArray(t_arr, i, on_Arr[j][1].substr(0, on_Arr[j][1].lastIndexOf(".")))) {
                        {
                            if (j > 0)
                                definition += " AND ";
                            definition += on_Arr[j][0] + "=" + on_Arr[j][1];
                            on_Arr.removeAt(j);
                            onErr = false;
                        }
                    }
                }
            }
            if (onErr) {
                alert("表关联错误，请检查关联设置！");
                return;
            }

            //--order sql
            var defOrder = "";
            for (var i = 0; i < order_Arr.length; i++) {
                if (i == 0)
                    defOrder += " ORDER BY ";
                else
                    defOrder += ",";
                if (defGroup.indexOf(order_Arr[i][0]) == -1 && grp)
                    defGroup += "," + order_Arr[i][0];
                defOrder += order_Arr[i][0] + " " + order_Arr[i][1];
            }
            //--Where sql
            if (defWhere.length > 0)
                definition += " WHERE " + defWhere.join(" AND ");

            //--GroupBy sql
            definition += defGroup;

            //--Having sql
            if (defHaving.length > 0)
                definition += " HAVING " + defHaving.join(" AND ");

            definition += defOrder;

        } else {
            definition = "SELECT " + c_arr.join(",") + " FROM " + t_arr.join(",");
        }
        $("#txt_Definition").val(definition);
    }
    else
        $("#txt_Definition").val("");
    $("#div_Definition").html($("#txt_Definition").val());
}

function addToArray(obj, arr) {
    for (var i = 0; i < obj.length; i++) {
        var push = true;
        var d = obj[i];
        var nm = d.name || d.id;
        if (jv.IsNull(nm)) push = false;
        if (typeof (d.value) == "undefined" || d.value == "-1") push = false;
        if (push) {
            arr.push(d.value);
        }
    }
}

//---------Where-----------------
function addWhere() {
    if (t_arr.length < 1) {
        alert("请选择视图！");
    }
    else {
        var i = $(".whereArea tr").length - 1;
        var addHtml = "<tr id='where_" + i + "'><td>" + formatDrop('dropViewColumn_' + i) + "</td><td>" + whereAction(i) + "<input type='text' name='whe_ActionText_" + i + "' class='whe_Action' style='width:150px;' /></td><td>" + formatGroup(i) +"</td><td>" + orderAction(i) + "</td><td>" + sortAction(i) + "</td><td><a onclick=\"deleteTr('where_" + i + "')\">删除</a></td></tr>";

        $(".whereAreaEnd").before(addHtml);
    }
}
function formatGroup(d) {
    var gp = "<select id='grp_GroupBy" + d + "' class='viewSelect'><option value=''>分组依据</option><option value='Min'>Min</option><option value='Max'>Max</option><option value='Count'>Count</option><option value='Where'>Where</option></select>";
    return gp;
}
function whereAction(d) {
    var wha = "<select id='wha_Action" + d + "'><option value='='>=</option><option value='!='>!=</option><option value='>'>></option><option value='<'><</option><option value=' like '>like</option><option value=' not like '>not like</option></select>";
    return wha;
}
function orderAction(d) {
    var od = "<select id='oda_SortType" + d + "'><option value='asc'>升序</option><option value='desc'>降序</option></select>";
    return od;
}
function sortAction(d) {
    var sort = "<select id='sor_SortNum" + d + "'>";
    for (var i = 1; i <= d + 1; i++) {
        sort += "<option value='" + i + "'>" + i + "</option>";
    }
    sort += "</select>";
    return sort;
}
function formatDrop(d) {
    var drop_F = "<select style=\"display: none\" onchange=\"DropChange(this.options[this.options.selectedIndex].value,'" + d + "')\">";
    var drop_S = "<select id='" + d + "' class='viewSelect'>";
    var defName;
    for (var i = 0; i < c_arr_all.length; i++) {
        var tbName = c_arr_all[i][0];
        tbName = tbName.substr(0, tbName.lastIndexOf("."));
        if (i == 0)
            defName = tbName;
        drop_F += "<option value='" + i + "'>" + tbName + "</option>";
    }
    for (var j = 0; j < c_arr_all[0].length; j++) {
        var tcName = c_arr_all[0][j];
        tcName = tcName.replace(defName + ".", "");
        drop_S += "<option value='" + c_arr_all[0][j] + "'>" + tcName + "</option>";
    }
    drop_F += "</select>";
    drop_S += "</select>";
    return drop_F + drop_S;
}
function DropChange(v, d) {
    $("#" + d).empty();
    for (var j = 0; j < c_arr_all[v].length; j++) {
        var tcName = c_arr_all[v][j];
        tcName = tcName.substr(tcName.lastIndexOf(".") + 1);
        $("#" + d).append("<option value='" + c_arr_all[v][j] + "'>" + tcName + "</option>");
    }
}

function CreateDefinition() {

    //----WHERE -------

    var err = false;
    $(".whereArea tr:not(.dmo) input").each(function () {
        if ($.trim($(this).val()) == "") {
            err = true;
            return;
        }
    });
    if (err) {
        alert("WHERE筛选器不能为空！");
        return;
    }
    where_Arr.splice(0, where_Arr.length);
    $(".whereArea tr:not(.dmo)").each(function (d) {
        var i = where_Arr.push("") - 1;
        where_Arr[i] = new Array();
        addToArray($(this).find("select,:text"), where_Arr[i]);
    });
    //--------Order By-----------
    order_Arr.splice(0, order_Arr.length);
    $(".orderByArea tr:not(.dmo)").each(function (d) {
        var i = order_Arr.push("") - 1;
        order_Arr[i] = new Array();
        addToArray($(this).find("select"), order_Arr[i]);
    });

    ShowDefinition(true);
}

//---------Definition------------ 
function ShowDefinition(useOn) {
    if (c_arr.length > 0 && c_arr[0].length > 0) {
        var definition = "";
        if (useOn) {
            //--------Check Where------------
            var grp = false; //是否分组
            var defGroup = "";
            var defSelect = c_arr;
            var defWhere = new Array();
            var defHaving = new Array();
            for (var i = 0; i < where_Arr.length; i++) {
                if (where_Arr[i][3] != "") {
                    grp = true;
                }
            }
            if (grp) {
                defGroup = " GROUP BY " + defSelect.join(",");
            }
            for (var i = 0; i < where_Arr.length; i++) {
                if (grp) {
                    if (where_Arr[i][3] == "Where")
                        defWhere.push(where_Arr[i][0] + where_Arr[i][1] + where_Arr[i][2]);
                    else if (where_Arr[i][3] != "") {
                        if (defGroup.indexOf(where_Arr[i][0]) == -1)
                            defGroup += "," + where_Arr[i][0];
                        var exf = where_Arr[i][3] + "(" + where_Arr[i][0] + ")";
                        var exfc = where_Arr[i][0].substr(where_Arr[i][0].lastIndexOf(".") + 1);
                        defHaving.push(exf + where_Arr[i][1] + where_Arr[i][2]);
                        for (var j = 0; j < defSelect.length; j++) {
                            for (var k = 0; k < defSelect[j].length; k++) {
                                if (defSelect[j][k] == where_Arr[i][0]) {
                                    defSelect[j][k] = exf + " as " + exfc;
                                }
                            }
                        }
                    }
                    else if (where_Arr[i][3] == "") {
                        if (defGroup.indexOf(where_Arr[i][0]) == -1)
                            defGroup += "," + where_Arr[i][0];
                        defHaving.push(where_Arr[i][0] + where_Arr[i][1] + where_Arr[i][2]);
                    }
                }
                else {
                    defWhere.push(where_Arr[i][0] + where_Arr[i][1] + where_Arr[i][2]);
                }
            }
            //--------Definition Sql------------
            var ship = " " + $('#viewShip input:radio:checked').val() + " "; //Join sql
            definition = "SELECT " + defSelect.join(",");

            //--On sql
            definition += " FROM " + t_arr[0];
            var onErr = false;
            for (var i = 1; i < t_arr.length; i++) {
                onErr = true;
                definition += " INNER JOIN " + t_arr[i] + " ON ";
                for (var j = 0; j < on_Arr.length; j++) {
                    if (CheckArray(t_arr, i, on_Arr[j][0].substr(0, on_Arr[j][0].lastIndexOf("."))) && CheckArray(t_arr, i, on_Arr[j][1].substr(0, on_Arr[j][1].lastIndexOf(".")))) {
                        {
                            if (j > 0)
                                definition += " AND ";
                            definition += on_Arr[j][0] + "=" + on_Arr[j][1];
                            on_Arr.removeAt(j);
                            onErr = false;
                        }
                    }
                }
            }
            if (onErr) {
                alert("表关联错误，请检查关联设置！");
                return;
            }

            //--order sql
            var defOrder = "";
            for (var i = 0; i < order_Arr.length; i++) {
                if (i == 0)
                    defOrder += " ORDER BY ";
                else
                    defOrder += ",";
                if (defGroup.indexOf(order_Arr[i][0]) == -1 && grp)
                    defGroup += "," + order_Arr[i][0];
                defOrder += order_Arr[i][0] + " " + order_Arr[i][1];
            }
            //--Where sql
            if (defWhere.length > 0)
                definition += " WHERE " + defWhere.join(" AND ");

            //--GroupBy sql
            definition += defGroup;

            //--Having sql
            if (defHaving.length > 0)
                definition += " HAVING " + defHaving.join(" AND ");

            definition += defOrder;

        } else {
            definition = "SELECT " + c_arr.join(",") + " FROM " + t_arr.join(",");
        }
        $("#txt_Definition").val(definition);
    }
    else
        $("#txt_Definition").val("");
    $("#div_Definition").html($("#txt_Definition").val());

    //-----ON-----
    if (t_arr.length > 1) {
        //        var divhtml = "";
        //        for (var i = 0; i < t_arr.length - 1; i++) {
        //            if ($("#on_" + i).length <= 0) {
        //                var addHtml = "<tr id='on_" + i + "'><td>" + formatDrop('dropLeftOn_' + i) + "</td><td>=</td><td>" + formatDrop('dropRightOn_' + i) + "</td><td><a onclick=\"deleteTr('on_" + i + "')\">删除</a></td></tr>";
        //                divhtml += addHtml;
        //            }
        //        }
        //        $(".onArea_end").before(divhtml);

//        if ($('#viewShip input:radio:checked').length == 0)
//            $("#viewShip input[type=radio]")[0].checked = true;
    } else {
        $(".onArea tr:not(.dmo)").remove();
    }
    if (t_arr.length < 1) {
        $(".whereArea tr:not(.dmo)").remove();
        $(".orderByArea tr:not(.dmo)").remove();
    }
}
